package com.itheima.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class LoginGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        //获取response
        ServerHttpResponse response = exchange.getResponse();
        //获取request中的token值
        String token = request.getQueryParams().getFirst("token");
        if("123456".equals(token)){
            //放行
            return chain.filter(exchange);
        }
        //设置返回拦截结果值401
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置处理完成
        return response.setComplete();
    }

    //标识返回值越低 表示 此过滤器的执行优先级比其他过滤器高
    @Override
    public int getOrder() {
        return -1;
    }
}
